import React, { useRef, useEffect } from "react";
import styles from "./index.module.less";
import editStyle from "./inputMain/index.module.less";
import InputHead from "./inputHead";
import InputMain from "./inputMain";
import { profile } from "@depjs/storage";
import { useParams } from "react-router-dom";
import toast from "@utils/showToast";
import socket from "@depjs/socketClient";
import { connect } from "react-redux";
import { recordCurrentRange } from "@redux/actions02";

const InputAreaMould = (props) => {
    const { recordCurrentRange } = props;

    const { id } = useParams();

    const sendBtn = useRef(null);

    useEffect(() => {
        document.onkeydown = function (e) {
            // 点击Enter键，且编辑区获取到焦点，但是没点击shift键的时候，就会发送消息
            if (
                e.key === "Enter" &&
                !e.shiftKey &&
                document.querySelector(`.${editStyle.edit}`) ===
                    document.activeElement
            ) {
                e.preventDefault(); // 阻止enter键的默认换行事件
                sendBtn.current.click();
            }
        };
    }, []);

    return (
        <div className={styles.input_area_mould}>
            <InputHead />
            <InputMain />
            <div className={styles.send_msg_wrap}>
                <div
                    className={styles.send_msg}
                    title="按Enter键发送，按Ctrl+Enter键换行"
                    ref={sendBtn}
                    onClick={() => {
                        const edit = document.querySelector(
                            `.${editStyle.edit}`
                        );
                        /**
                         * 这里必须去掉<span>、<!--StartFragment-->标签，以及两个标签之间的空格，不然影响样式
                         * <!--EndFragment-->和</span>同理
                         */
                        const content = edit.innerHTML
                            .replace(/(<span>)(\s*)(<!--StartFragment-->)/g, "")
                            .replace(
                                /(<!--EndFragment-->)(\s*)(<\/span>)/g,
                                ""
                            );
                        if (!content) {
                            toast.fail("不能发送空白信息");
                            return;
                        }
                        const messages = [];
                        const images = [];
                        const space = "____";
                        let changes;
                        if (content.includes("<img")) {
                            changes = content.replace(
                                /(<img).*?>/g,
                                (match) => {
                                    console.log("match: ", match);
                                    if (!match.includes("emoji_img")) {
                                        images.push(match);
                                        return space;
                                    }
                                    return match;
                                }
                            );
                            const arr = changes.split(space);
                            arr.forEach((item, index) => {
                                if (
                                    item &&
                                    item
                                        .replace(
                                            /(&nbsp;)|(<\/span>)|(<br>)|(<span>)/g,
                                            ""
                                        )
                                        .trim()
                                ) {
                                    messages.push({
                                        from: profile.userName,
                                        to: id,
                                        content: item,
                                        messageType: "TEXT",
                                    });
                                }
                                if (images[index]) {
                                    messages.push({
                                        from: profile.userName,
                                        to: id,
                                        content: images[index],
                                        messageType: "IMAGE",
                                    });
                                }
                            });
                        } else {
                            messages.push({
                                from: profile.userName,
                                to: id,
                                content,
                                messageType: "TEXT",
                            });
                        }
                        messages.forEach((item) => {
                            socket.emit("send chat message", item);
                        });

                        edit.innerHTML = "";

                        // 发送消息后，取消选区，并恢复光标位置
                        const selection = window.getSelection();
                        selection.collapseToStart();
                        const range = selection.getRangeAt(0);
                        range.collapse(true);
                        recordCurrentRange(range);
                    }}
                >
                    发送(S)
                </div>
            </div>
        </div>
    );
};

export default connect((state) => state, { recordCurrentRange })(
    InputAreaMould
);
